<template>
  <div class="tags-tabs-style">
    <Tabs
      v-model="activeTagsName"
      type="card"
      closable
      @on-click="handleTabClick"
      @on-tab-remove="handleTabRemove"
    >
      <TabPane
        v-for="(item, index) in getTag"
        :key="index"
        :label="item.title"
        :name="item.path"
      ></TabPane>
    </Tabs>
  </div>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
  name: "yui-tags-tab",
  data() {
    return {
      activeTagsName: ""
    };
  },
  computed: {
    ...mapGetters({
      getTag: "tagsView/getTag"
    })
  },
  watch: {
    $route() {
      this.handleRouteChange();
    }
  },
  methods: {
    ...mapActions({
      addTag: "tagsView/addTag",
      delTag: "tagsView/delTag"
    }),
    //点击标签切换页面
    handleTabClick(path) {
      const rs = this.getTag.filter(item => {
        return path === item.path;
      })[0];
      if (path !== this.$route.path) {
        this.$router.push({ path: path, query: rs.query, params: rs.params });
      }
    },
    //添加页面
    handleRouteChange() {
      this.activeTagsName = this.activeTagsName = this.$route.path;
      this.addTag(this.$route);
    },
    //标签关闭时触发
    handleTabRemove(path) {
      this.delTag(path).then(response => {
        // 只有在关闭当前打开的标签页才会有影响
        let lastView;
        if (response.tagIndex === response.visitedTag.length) {
          lastView = response.visitedTag.slice(-1)[0]; // 选取路由数组中的最后一位
        } else {
          lastView = response.visitedTag.slice(response.tagIndex)[0]; // 选取路由数组中的最后一位
        }
        if (lastView) {
          this.$router.push({ path: lastView.path });
        } else {
          this.$router.push({ path: "/" });
        }
      });
    }
  }
};
</script>
<style></style>
